import { NavBar } from 'antd-mobile'

import { getSearchResultListAPI } from '@/api/home'
import ArticleItem from '@/components/ArticleItem'
import { ArticlesItem } from '@/types/data.d.'
import { history } from '@/utils/history'
import { InfiniteScroll } from 'antd-mobile'
import { useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import styles from './index.module.scss'

const Result = () => {
  const params = useParams()
  const navigate = useNavigate()
  // 1. 列表数据的变量
  const [data, setData] = useState<ArticlesItem[]>([])
  const [hasMore, setHasMore] = useState(true)
  console.log(params.q)
  async function loadMore() {
    if (!params.q) return
    // 发送请求获取数据
    const { data } = await getSearchResultListAPI({ q: params.q })
    // 向列表中追加数据
    setData((list) => [...list, ...data.results])
    // 判断是否还有数据 =》如果数据设置为 true 可以继续滚动加载数据；没有数据设置为false 不会再继续滚动加载数据
    if (!(data.total_count * data.per_page < data.total_count))
      setHasMore(false)
  }
  const renderArticleList = () => {
    return (
      <div className={styles.root}>
        {/* 文章列表中的每一项 */}
        {data.map((item) => (
          <div
            className="article-item"
            key={item.art_id}
            onClick={() => navigate('/article/' + item.art_id)}>
            <ArticleItem type={item.cover.type} item={item} />
          </div>
        ))}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </div>
    )
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">{renderArticleList()}</div>
    </div>
  )
}

export default Result
